package com.pozheg;

import android.app.*;
import android.content.*;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.EditText;

/**
 * The simple application to play remote audio stream
 * It allows to enter remote URL, start and stop playing it.
 * User is allowed to play stream only when WIFI connection available.
 *
 * @author Eugeny Pozharsky
 */
public class MyActivity extends Activity implements View.OnClickListener
{
    PlayerService mService;
    boolean mBound = false;
    PlayerCallback callback = new DefaultPlayerCallback();

    public static final int DIALOG_PROGRESS = 1;
    public static final int DIALOG_INVALID_STREAM = 2;
    public static final int DIALOG_NO_WIFI = 3;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.btnPlay).setOnClickListener(this);
        findViewById(R.id.btnStop).setOnClickListener(this);

        // Bind PlayerService
        Intent intent = new Intent(this, PlayerService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * Called when activity destroying.
     * We have to destroy MediaPlayer to avoid resources leaks
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Unbind PlayerService
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * Called when system try to create dialog.
     * This application supports 3 types of dialog - progress, invalid stream alert and no wifi alert.
     * @param id id of the dialog
     * @return dialog instance
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        if (id == DIALOG_PROGRESS) {
            dialog = ProgressDialog.show(MyActivity.this, "", "Opening...", true);
        } else
        if (id == DIALOG_INVALID_STREAM) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Error opening stream.")
                    .setCancelable(false)
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                        }
                    });
            dialog = builder.create();
        } else
        if (id == DIALOG_NO_WIFI) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("No WIFI connection available.")
                    .setCancelable(false)
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                        }
                    });
            dialog = builder.create();
        }
        return dialog;
    }

    /**
     * Checks that wifi enabled.
     * @return true if wifi enabled.
     */
    private boolean isWifiEnabled() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo.State wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        return (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING);
    }

    /**
     * Called when user click on 'Play' or 'Stop' button.
     * @param view button instance
     */
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btnStop) {
            if (mBound) {
                mService.stop();
            }
        } else if (view.getId() == R.id.btnPlay) {
            if (!isWifiEnabled()) {
                MyActivity.this.showDialog(DIALOG_NO_WIFI);
            } else {
                if (mBound) {
                    mService.start(((EditText) view.getRootView().findViewById(R.id.edUrl)).getText().toString());
                }
            }
        }
    }

    /**
     * Defines callbacks for service binding, passed to bindService()
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // We've bound to PlayerService, cast the IBinder and get PlayerService instance
            PlayerService.LocalBinder binder = (PlayerService.LocalBinder) service;
            mService = binder.getService();
            mBound = true;
            mService.setCallback(callback);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

    /**
     * Default implementation of callback interface
     */
    private class DefaultPlayerCallback implements PlayerCallback {
        @Override
        public void onStarted() {
            MyActivity.this.dismissDialog(DIALOG_PROGRESS);
        }

        @Override
        public void onStopped() {
            MyActivity.this.findViewById(R.id.btnPlay).setEnabled(true);
            MyActivity.this.findViewById(R.id.btnStop).setEnabled(false);
        }

        @Override
        public void onStartFailed() {
            MyActivity.this.showDialog(DIALOG_INVALID_STREAM);
            MyActivity.this.findViewById(R.id.btnPlay).setEnabled(true);
            MyActivity.this.findViewById(R.id.btnStop).setEnabled(false);
        }

        @Override
        public void onPreStart() {
            MyActivity.this.findViewById(R.id.btnStop).setEnabled(true);
            MyActivity.this.findViewById(R.id.btnPlay).setEnabled(false);
            MyActivity.this.showDialog(DIALOG_PROGRESS);
        }
    }
}
